package com.spring.security.web.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.spring.security.core.context.JedisCont;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.model.Role;
import com.spring.security.web.model.User;
import com.spring.security.web.security.Contents;
import com.spring.security.web.security.PermissionSign;
import com.spring.security.web.security.RoleSign;
import com.spring.security.web.service.RoleService;
import com.spring.security.web.service.UserService;

/**
 * 用户控制器
 * 
 * @author StarZou
 * @since 2014年5月28日 下午3:54:00
 **/
@Controller
@RequestMapping(value = "/user")
public class UserController {

    static Logger logger = Logger.getLogger(UserController.class.getName());
    @Resource
    private UserService userService;

    /**
     * 用户登录
     * 
     * @param user
     * @param result
     * @return
     */
    @RequestMapping(value = "/login")
     public ModelAndView login(@Valid User user, BindingResult result, Model model, HttpServletRequest request) {
        Map s= new HashMap();
        logger.info("---->登陆");
        try {
            Subject subject = SecurityUtils.getSubject();
            // 已登陆则 跳到首页
            if (subject.isAuthenticated()) {
                return new ModelAndView("index",s);
            }
            if (result.hasErrors()) {
                model.addAttribute("error", "参数错误！");
                return new ModelAndView("login",null);
            }
            // 身份验证
            System.out.println("denglu------>1"+user.getUsername()+","+user.getPassword());
            subject.login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
            System.out.println("denglu------>3");
            // 验证成功在Session中保存用户信息
            final User authUserInfo = userService.selectByUsername(user.getUsername());
            request.getSession().setAttribute(Contents.USER_INFO, authUserInfo);
            s.put("user",authUserInfo);
            //request.getSession().getId();   sessionid
        } catch (AuthenticationException e) {
            // 身份验证失败
            model.addAttribute("error", "用户名或密码错误 ！");
            return new ModelAndView("login",null);
        }
        //登陆成功
        return new ModelAndView("index",s);
    }

    @RequestMapping(value = "/appLogin", method = RequestMethod.POST)
    public String appLogin(@Valid User user, BindingResult result, Model model, HttpServletRequest request) {
        logger.info("---->app登陆");
        try {
            Subject subject = SecurityUtils.getSubject();
            // 已登陆则 跳到首页
            if (subject.isAuthenticated()) {
                return "redirect:/";
            }
            if (result.hasErrors()) {
                model.addAttribute("error", "参数错误！");
                return "login";
            }
            // 身份验证
            subject.login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
            // 验证成功在Session中保存用户信息
            final User authUserInfo = userService.selectByUsername(user.getUsername());
            request.getSession().setAttribute("userInfo", authUserInfo);
            //request.getSession().getId();   sessionid
        } catch (AuthenticationException e) {
            // 身份验证失败
            model.addAttribute("error", "用户名或密码错误 ！");
            return "login";
        }
        //登陆成功
        return "redirect:/";
    }

    /**
     * 注册提交
     * @param user
     * @param role_id
     * @param result
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView register(@Valid User user,String role_id,BindingResult result, Model model,
                                 @RequestParam(value = "file", required = false)MultipartFile file,
                                 HttpServletRequest request) {
        logger.info("---->用户注册");
        String msg = "用户注册成功";
        Map m = new HashMap();
        if(!user.getPassword().equals(user.getPassword_again())){
            msg = "密码两次输入不一致";
            m.put("msg",msg);
            return new ModelAndView("user/register",m);
        }
        if(!ApplicationUtils.isNotNull(role_id)){
            msg = "请选择角色";
            m.put("msg",msg);
            return new ModelAndView("user/register",m);
        }
        user.setId(ApplicationUtils.randomUUID());
        user.setState("1");
//        String pwd = user.getPassword();
//        user.setPassword(PWD.createNewPassword(user.getPassword()));
        try{
            User is_exists = userService.selectByUsername(user.getUsername());
            if(ApplicationUtils.isNotNull(is_exists)){
                msg = "用户已存在";
                m.put("msg",msg);
                List<Role> roles = roleService.selectRoles(RoleSign.PARENT);
                m.put("rolelist",roles);
                return new ModelAndView("user/register",m);
            }

            if (!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                Date d = new Date();
                SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
                String newfilename = tempDate.format(d)+"_"+fileName;
                Integer fileSize = 0;
                File filePath = null;
                byte[] bytes = file.getBytes();
                fileSize = (int) file.getSize() / 1024;
                if (fileSize <= 102400) {
                    String path = request.getRealPath("");
                    String uploadPath = path+"\\upload\\";
                    //String uploadPath = JedisCont.APP_ADDRESS;
                    if(!(new File(uploadPath).isDirectory())){
                        new File(uploadPath).mkdir();
                    }
                    uploadPath+=newfilename;
                    filePath = new File(uploadPath);
                    FileCopyUtils.copy(bytes, filePath);
                    user.setImage_src(JedisCont.APP_ADDRESS+newfilename);
                } else {
                    msg = "上传的文件太大，文件大小不能超过10M";
                    m.put("msg",msg);
                    return new ModelAndView("user/register",m);
                }
            }
            userService.insert(user,role_id);

            Subject subject = SecurityUtils.getSubject();
            // 身份验证
            subject.login(new UsernamePasswordToken(user.getUsername(),user.getPassword()));
            // 验证成功在Session中保存用户信息
            User authUserInfo = userService.selectByUsername(user.getUsername());
            request.getSession().setAttribute(Contents.USER_INFO, authUserInfo);
        }catch(Exception e){
            e.printStackTrace();
            msg = "用户注册失败";
        }

        m.put("msg",msg);
        return new ModelAndView("user/register_ok",m);
    }

    @Resource
    private RoleService roleService;

    /**
     * 跳转到注册界面
     * @return
     */
    @RequestMapping("/registerPage")
    public ModelAndView registerPage() {
        Map m = new HashMap();
        //try{
            List<Role> roles = roleService.selectRoles(RoleSign.PARENT);
            m.put("rolelist",roles);
        //}catch (Exception e){
        //    e.printStackTrace();
        //}
        return new ModelAndView("user/register",m);
    }

    /**
     * 用户登出
     * 
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        //JSON.Decode("");
        System.out.print("---------->登出");
        session.removeAttribute(Contents.USER_INFO);
        // 登出操作
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    /**
     * 基于角色 标识的权限控制案例
     */
    @RequestMapping(value = "/admin")
    //@ResponseBody
    @RequiresRoles(value = RoleSign.PARENT)
    public String admin() {
        //拥有家长权限
        return "demo/index";
    }

    /**
     * 基于权限标识的权限控制案例
     */
    @RequestMapping(value = "/create")
    @ResponseBody
    @RequiresPermissions(value = PermissionSign.USER_CREATE)
    public String create() {
        return "拥有user:create权限,能访问";
    }


    /**
     * 附件保存
     *
     * @return
     * @throws Exception
     */
//    @RequestMapping(value = "/attcahSave", method = RequestMethod.POST)
//    public String attcahSave(HttpServletRequest request, String t_cguid,String lz_cguid,
//                             @RequestParam(value = "file", required = false)MultipartFile file) {
//        String ret="上传成功";
//        Map<String, String> map = new HashMap<String, String>();
//        TUser user = (TUser) request.getSession().getAttribute(
//                Constants.USER_INFO_SESSION);
//        String cguid = htxx.getCguid();
//        map.put("cguid", cguid);
//        //List<Xmglbb> xmglbbList = xmglService.getXmglBbsjList(map);
//        String oldatt = "";
//        if (!file.isEmpty()) {
//            try {
//                String fileName = file.getOriginalFilename();
//                Date d = new Date();
//                SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
//                String newfilename = cguid+tempDate.format(d)+"_"+fileName;
////				String[] suffixs = fileName.split("\\.");
////				String suffix = "." + suffixs[suffixs.length - 1];
//                Integer fileSize = 0;
//                File filePath = null;
//                //if ((".zip.rar.gz.tar.bz2".indexOf(suffix.toLowerCase()) != -1)) {
//                byte[] bytes = file.getBytes();
//                fileSize = (int) file.getSize() / 1024;
//                if (fileSize <= 102400) {
//                    String path = request.getRealPath("");
////						if(!(new File("D:/BBSJ/upload/").isDirectory())){
////							new File("D:/BBSJ/").mkdir();
////							new File("D:/BBSJ/upload/").mkdir();
////						}
//                    String uploadPath = path+"\\upload\\" + newfilename;
//                    filePath = new File(uploadPath);
////						filePath = new File(request.getSession()
////								.getServletContext().getRealPath(uploadPath));
//                    FileCopyUtils.copy(bytes, filePath);
//                    map.put("t_cguid", t_cguid);
//                    map.put("t_name", fileName);
//                    map.put("t_sourcename", newfilename);
//                    map.put("lz_cguid", lz_cguid);
//                    map.put("add_user", user.getUSERID());
//                    map.put("add_dep", user.getSWJG_DM());
//                    taskTransferService.insertFileTable(map);
//                } else {
//                    ret = "上传的文件太大，文件大小不能超过10M";
//                }
//                //} else {
//                //	ret = "上传的文件格式不支持";
//                //}
//            } catch (IOException e) {
//                e.printStackTrace();
//                return "task/transfer/upfileret";
//            }
//            //删除老的附件
////			try{
////				if(htxx.isNotNull(oldatt)){
////					File oldfile = new File(oldatt);
////					oldfile.delete();
////				}
////			}catch(Exception e){
////				e.printStackTrace();
////			}finally{
////			}
//        }
//        request.setAttribute("ret",ret);
//        return "task/transfer/upfileret";
//    }

}
